/*
 * @Description:
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-21 17:53:43
 */
/**
 * @Description:
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-10 09:55:16
 */
import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import tailWindcss from '@tailwindcss/vite'
import { PostcssPxToViewport } from './plugin/postcss-px-to-viewport'
import unoCss from 'unocss/vite'
import { presetIcons, presetAttributify, presetWind3 } from 'unocss'
import { visualizer } from 'rollup-plugin-visualizer'
import { VitePWA } from 'vite-plugin-pwa'

import tsx from './plugin/index'

console.log('vite.config.ts process.env: ', process.env)

// https://vite.dev/config/
export default ({ mode }: any) => {
  console.log('vite.config.ts mode: ', mode)
  // process.cwd() 获取项目根目录
  console.log('vite.config.ts loadEnv process.env: ', loadEnv(mode, process.cwd()))

  return defineConfig({
    plugins: [
      vue({
        template: {
          compilerOptions: {
            isCustomElement:(tag) => {
              tag.includes('IAWebComponent-')
            }
          }
        }
      }),
      // vueJsx(),
      tsx(),
      AutoImport({
        imports: ['vue'],
        dts: 'src/auto-imports.d.ts',
      }),
      tailWindcss(),
      unoCss({
        rules: [
          ['flex', { display: 'flex' }],
          ['red', { color: 'red' }],
          [/^m-(\d+)$/, ([, d]) => ({ margin: `${Number(d) * 10}px` })],
        ],
        shortcuts: {
          cike: ['flex', 'red'],
        },
        presets: [presetIcons(), presetAttributify(), presetWind3()],
      }),
      visualizer({
        open: true,
      }),
      VitePWA({
        workbox: {
          cacheId: 'XIaoman', //缓存名称
          runtimeCaching: [
            {
              urlPattern: /.*\.js.*/, //缓存文件
              handler: 'StaleWhileRevalidate', //重新验证时失效
              options: {
                cacheName: 'XiaoMan-js', //缓存js，名称
                expiration: {
                  maxEntries: 30, //缓存文件数量 LRU算法
                  maxAgeSeconds: 30 * 24 * 60 * 60, //缓存有效期
                },
              },
            },
          ],
        },
      }),
      vueDevTools(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/bem.scss" as *;`,
        },
      },
      postcss: {
        plugins: [PostcssPxToViewport()],
      },
    },
    build: {
      chunkSizeWarningLimit: 2000,
      cssCodeSplit: true,
      sourcemap: false,
      minify: 'terser',
      assetsInlineLimit: 4000,
    },
  })
}
